package interceptor

import (
	"github.com/gin-gonic/gin"
	"http_server/src/common_util"
	"http_server/src/rpc_client"
	"http_server/src/utils"
	"net/http"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		authFlag := 0
		if authHeader != "" {
			tokens := strings.Split(authHeader, ":")
			if len(tokens) == 2 {
				rsp, err := rpc_client.RPCCall(common_util.TokenAuthenticationMethod, tokens[0], tokens[1])
				if err != nil {
					common_util.ErrorLogger.Printf("调用鉴权接口出现错误：%v", err)
				}
				authFlag = utils.TransInterfaceToInt(rsp)
			}
		}
		if authFlag == 0 {
			c.Abort()
			utils.RespondWithJSON(c, http.StatusBadRequest, "未授权用户，请重新登录", nil)
			return
		}
		if authFlag == -1 {
			c.Abort()
			utils.RespondWithJSON(c, http.StatusInternalServerError, "服务器内部错误", nil)
			return
		}
		c.Next()
	}
}
